﻿using DAL;
using IService;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Model;
using NPOI.OpenXmlFormats.Wordprocessing;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;

namespace Service
{
    public class BiSupplierService : IBiSupplierService
    {
        private readonly BiSupplierDal _biSupplier;
        private readonly INumberingRuleService _numberingRuleService;
        private readonly ILogger<BiSupplierService> _logger;
        private readonly AppDbContext _context;
        public BiSupplierService(BiSupplierDal biSupplier, INumberingRuleService numberingRuleService, ILogger<BiSupplierService> logger, AppDbContext context)
        {
            _biSupplier = biSupplier;
            _numberingRuleService = numberingRuleService;
            _logger = logger;
            _context = context; 
        }

        /// <summary>
        /// 新增供应商：调用编号规则生成编码（rule_id=11）
        /// </summary>
        public async Task<int> CreateAsync(BiSupplier data)
        {
            try
            {
                // 调用编号规则生成供应商编码（rule_id=11）
                string supplierCode = await _numberingRuleService.GenerateAndUpdateNumberAsync(11);
                data.SupplierCode = supplierCode;

                // 保存供应商数据
                int result = await _biSupplier.CreateAsync(data);
                _logger.LogInformation("供应商新增成功，编码：{SupplierCode}", supplierCode);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建供应商失败");
                throw;
            }
        }

        /// <summary>
        /// 生成预览编码（不更新数据库，仅预览）
        /// </summary>
        public async Task<string> GeneratePreviewCodeAsync()
        {
            try
            {
                return await _numberingRuleService.GenerateNumberByRuleIdAsync(11);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成供应商预览编码失败");
                throw;
            }
        }

        /// <summary>
        /// 简单新增方法（如果不需要事务保护）
        /// </summary>
        public Task<(bool success, string message)> SimpleCreateAsync(BiSupplier data)
        {
            // 若需要简单创建逻辑，也需同步修改编码生成方式（建议统一使用CreateAsync）
            throw new NotImplementedException("推荐使用CreateAsync方法，已集成编码生成逻辑");
        }

        public async Task<int> DeleteAsync(long supplierId)
        {
            try
            {
                // 先查询数据，确认存在再删除（增加日志便于排查）
                var supplier = await _biSupplier.GetByIdAsync(supplierId);
                if (supplier == null)
                {
                    _logger.LogWarning("删除失败：未找到供应商，ID：{SupplierId}", supplierId);
                    return 0;
                }
                // 调用DAL层修正后的DeleteAsync
                var result = await _biSupplier.DeleteAsync(supplierId);
                if (result > 0)
                {
                    _logger.LogInformation("删除成功：供应商ID：{SupplierId}", supplierId);
                }
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除供应商失败，ID：{SupplierId}", supplierId);
                throw; // 抛出异常，让Controller捕获并返回错误信息
            }
        }

        public async Task<List<BiSupplier>> GetAllAsync()
        {
            try
            {
                return await _biSupplier.GetAllAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询所有供应商失败");
                throw;
            }
        }

        public async Task<BiSupplier> GetByIdAsync(long supplierId)
        {
            try
            {
                return await _biSupplier.GetByIdAsync(supplierId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询供应商失败，ID：{SupplierId}", supplierId);
                throw;
            }
        }

        public async Task<int> UpdateAsync(BiSupplier data)
        {
            try
            {
                // 先从数据库获取现有实体
                var existingSupplier = await _biSupplier.GetByIdAsync(data.SupplierId);
                if (existingSupplier == null)
                {
                    _logger.LogWarning("更新失败：未找到供应商，ID：{SupplierId}", data.SupplierId);
                    return 0;
                }

                // 只更新允许修改的字段，保留创建相关信息
                existingSupplier.SupplierName = data.SupplierName;
                existingSupplier.Industry = data.Industry;
                existingSupplier.CustomerSource = data.CustomerSource;
                existingSupplier.ContactPerson = data.ContactPerson;
                existingSupplier.ContactPhone = data.ContactPhone;
                existingSupplier.Email = data.Email;
                existingSupplier.Status = data.Status;
                existingSupplier.Address = data.Address;
                existingSupplier.Remarks = data.Remarks;
                existingSupplier.AccountName = data.AccountName;
                existingSupplier.TaxpayerId = data.TaxpayerId;
                existingSupplier.BankAccount = data.BankAccount;
                existingSupplier.OpeningBank = data.OpeningBank;
                existingSupplier.BankAddress = data.BankAddress;
                existingSupplier.AttachmentId = data.AttachmentId;
                existingSupplier.CustomerId = data.CustomerId;

                // 只更新修改时间和修改人
                existingSupplier.UpdateTime = DateTime.Now;
                existingSupplier.UpdateBy = data.UpdateBy;

                // 调用DAL层更新
                return await _biSupplier.UpdateAsync(existingSupplier);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新供应商失败，ID：{SupplierId}", data.SupplierId);
                throw;
            }
        }

        /// <summary>
        /// 导出选中供应商数据
        /// </summary>
        /// <param name="supplierIds">选中的供应商ID集合</param>
        /// <returns>Excel文件流</returns>
        public async Task<MemoryStream> ExportAsync(List<long> supplierIds)
        {
            try
            {
                // 查询选中的供应商数据
                var suppliers = new List<BiSupplier>();
                foreach (var id in supplierIds)
                {
                    var supplier = await _biSupplier.GetByIdAsync(id);
                    if (supplier != null)
                        suppliers.Add(supplier);
                }

                // 使用EPPlus创建Excel
                using var package = new ExcelPackage();
                var worksheet = package.Workbook.Worksheets.Add("供应商数据");

                // 设置表头
                var headers = new List<string>
                {
                    "供应商编号", "供应商名称", "状态", "所属行业", "联系人", "联系电话",
                    "电子邮箱", "地址", "开户行", "银行账号", "纳税人识别号", "创建人", "创建时间"
                };
                for (int i = 0; i < headers.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = headers[i];
                    worksheet.Cells[1, i + 1].Style.Font.Bold = true;
                    worksheet.Cells[1, i + 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                }

                // 填充数据
                for (int row = 0; row < suppliers.Count; row++)
                {
                    var supplier = suppliers[row];
                    worksheet.Cells[row + 2, 1].Value = supplier.SupplierCode;
                    worksheet.Cells[row + 2, 2].Value = supplier.SupplierName;
                    worksheet.Cells[row + 2, 3].Value = supplier.Status == "1" ? "启用" : "禁用";
                    worksheet.Cells[row + 2, 4].Value = supplier.Industry;
                    worksheet.Cells[row + 2, 5].Value = supplier.ContactPerson;
                    worksheet.Cells[row + 2, 6].Value = supplier.ContactPhone;
                    worksheet.Cells[row + 2, 7].Value = supplier.Email;
                    worksheet.Cells[row + 2, 8].Value = supplier.Address;
                    worksheet.Cells[row + 2, 9].Value = supplier.OpeningBank;
                    worksheet.Cells[row + 2, 10].Value = supplier.BankAccount;
                    worksheet.Cells[row + 2, 11].Value = supplier.TaxpayerId;
                    worksheet.Cells[row + 2, 12].Value = supplier.CreateBy;
                    worksheet.Cells[row + 2, 13].Value = supplier.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                }

                // 自动调整列宽
                worksheet.Cells.AutoFitColumns();

                // 转换为内存流
                var stream = new MemoryStream();
                package.SaveAs(stream);
                stream.Position = 0;

                _logger.LogInformation("导出供应商数据成功，共{Count}条", suppliers.Count);
                return stream;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出供应商数据失败");
                throw;
            }
        }


    }
}